#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<netdb.h>

#define STRDUP_ALLOCA(ptr,str) do{              \
    (ptr) = (char *)alloca(strlen(str) + 1);    \
    strcpy(ptr,str);                            \
  }while(0)

int select_fd(int fd,int maxtime,int writep)
{
  fd_set fds,exeptfds;
  struct timeval timeout;
  FD_ZERO(&fds);
  FD_SET(fd,&fds);
  FD_ZERO(&exeptfds);
  FD_SET(fd,&exeptfds);
  timeout.tv_sec = maxtime;
  timeout.tv_usec = 0;
  return select(fd + 1,writep?NULL:&fds,writep?&fds:NULL,
                &exeptfds,&timeout);
}

int iwrite(int fd,char *buf,int len)
{
  int res = 0;
  while(len>0)
    {
      do{
        if(900)
          {
            do
              {
                res = select_fd(fd,2,1);
              }
            while(res ==  -1);
            if(res <= 0)
              {
                if(res == 0)
                  {//I hope It could do something here;
                  }
                return  -1;
              }
          }
        res = write(fd,buf,len);
      }
      while(res ==  -1);
      if(res <= 0)
        break;
      buf += res;
      len = len - res;
    }
  return res;
}

int iread(int fd,char *buf,int len)
{
  int errno;
  int res;
  do{
    if(900)
      {
        do
          {
            res = select_fd (fd, 90 , 0);
          }
        while(res == -1);
          if(res <= 0)
            {
              if(res == 0)
                errno = 0;
              return  -1;
            }
      }
    res = recv (fd, buf, len,0);
  }
  while(res ==  -1);
  
  return res;
}

int getHeader(char *a,int bufsize)
{
  if (bufsize == 0) {
    return 0;
  }
  //  char *p = a;
  char *start = a;
  char *end = a;
  while(*end != '\0')
    {
      if (*end == '\r'&&*(end + 1) == '\n') {
        if (start == end) {
          return end + 2 - a;
        }
        else
          {
            start = end + 2;
            end = start;
            continue;
          }
      }
      end++;
    }
  return 0;
}

int main(int argc, char *argv[])
{
  //http://www.aisex.com/bt/thread.php?fid=4
  //http://dict.cn/mini.php?q=abc
  //http://dvd39.net/upload/product_images/R07239/b.jpg
  //http://img2.mtime.com/up/809/472809/c544deed-596d-4ae0-aa00-2c09643dcf6a_500.jpg
  const char *hostname = "img2.mtime.com";
  //http://www.google.com/intl/en_ALL/images/logo.gif
  const char *command = "GET";
  const char *path = "/up/809/472809/c544deed-596d-4ae0-aa00-2c09643dcf6a_500.jpg";
  //  const char *useragent = "diwu";
  const char *useragent = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
  int hostport = 80;
  struct hostent *hp;
  struct in_addr in;
  struct sockaddr_in sock_name;
  char *request = (char *) malloc(sizeof(hostname) + sizeof(path) + sizeof(useragent) + sizeof(hostport) + 200);
  memset(request,'\0',200);
  //= "GET /australia.htm HTTP/1.0\r\nUser-Agent: Wget/1.5.3\r\nHost: www.dict.cn:80\r\nAccept: */*\r\n\r\n";
  sprintf(request,"\
%s %s HTTP/1.0\r\n\
User-Agent: %s\r\n\
Host: %s:%d\r\n\
Accept: */*\r\n\r\n",command,path,useragent,hostname,hostport);
  int int_for_sock = 0;
  int *sock = &int_for_sock;
  char *inet_s;
  static char c[8000];

  hp = gethostbyname(hostname);
  unsigned long int addr;
  addr = inet_addr(hostname);


  memcpy(&sock_name.sin_addr,hp -> h_addr_list[0],hp -> h_length);
  memcpy(&in,*hp -> h_addr_list,sizeof(in));
  sock_name.sin_family = AF_INET;
  sock_name.sin_port = htons(80);
  STRDUP_ALLOCA(inet_s,inet_ntoa(in));
  if((*sock = socket(AF_INET,SOCK_STREAM,0)) ==  -1)
    return 1;

  if(connect(*sock,(struct sockaddr *)&sock_name,sizeof(sock_name)))
    return 1;
  FILE *fp;
  if(!(fp = fopen("1.jpg","w")))
    {
      printf("can not open test.html\n");
      exit(1);
    }

  iwrite(*sock,request,strlen(request));
  int res = 1;
  while(res>0){
    int offset = 0;
    memset(c,'\0',sizeof(c));
    res = iread(*sock,c,sizeof(c));
    offset = getHeader(c,res);
    if (offset > 0) {
      fwrite(c - offset,sizeof(char),res - offset,fp);
      continue;
    }
    printf("****************************************\n");
    printf("%s",c);
    //    fprintf(fp,"%s",c);
    fwrite(c,sizeof(char),res,fp);
    printf("\n\n");
    printf("****************************************\n");
  }
  close(*sock);
  return 0;
}
